// Package afos provide an afero OS FS access layer
package afos

import (
	"errors"
	"os"

	"github.com/spf13/afero"

	"github.com/fclairamb/ftpserver/config/confpar"
)

// ErrMissingBasePath is triggered when the basePath property isn't specified
var ErrMissingBasePath = errors.New("basePath must be specified")
var ErrNoPermissionCreateBasePath = errors.New("basePath can not to be create")
var ErrAlreadyExsitsFile = errors.New("basePath is a file")

// LoadFs loads a file system from an access description
func LoadFs(access *confpar.Access) (afero.Fs, error) {
	basePath := access.Params["basePath"]
	if basePath == "" {
		return nil, ErrMissingBasePath
	}
	fi, err := os.Stat(basePath)
	if err != nil {
		if os.IsNotExist(err) {
			merr := os.MkdirAll(basePath, 0755)
			if merr != nil {
				return nil, ErrNoPermissionCreateBasePath
			}
		}
		return nil, err
	} else {
		if !fi.IsDir() {
			return nil, ErrAlreadyExsitsFile
		}
	}
	return afero.NewBasePathFs(afero.NewOsFs(), basePath), nil
}
